import utils.signals
from django.contrib.auth.models import User
from StartGroup.models import Group
from groupMembers.models import Member_Group
from contifyuser.models import Member
import connectpeople.Constants
from datetime import datetime
from django.http import HttpResponseRedirect as redirect
from django.shortcuts import render_to_response
from django.template import RequestContext
from django.core.paginator import Paginator
from django.utils.safestring import mark_safe
import simplejson
from django.http import HttpResponse

# Join Group
def joinGroup(request):
    
    # Obtain user
    userid = request.session[connectpeople.Constants.session_userid]
    
    # Obtain group_web_address
    group_addr = request.session[connectpeople.Constants.session_group_web_address]
    group_info = getGroupFromWebAddr(group_addr)
    
    mem_grp = Member_Group(group=group_info, user_id=userid, join_date=datetime.now())
    mem_grp.save()
    
    #Email parameters
    # Get email ids of these users
    recipient = User.objects.filter(username=userid).values_list('email', flat=True)
    # Compose subject for the email
    subj = group_info.group_name + " joined"
    # name of the recipeint
    rec_name = userid
    
    utils.signals.send_single_mail.send(
       sender=Group, email=recipient, name=rec_name, model=group_info, subject=subj, template="email/groupJoinEmail.html")
    
    return redirect("../../connectpeople/startGroup/" +group_addr)

# View Members
def member_view(request):
    
    if connectpeople.Constants.session_group_web_address in request.session:
        group_web_addr = request.session[connectpeople.Constants.session_group_web_address]
        group = getGroupInfo(group_web_addr)
            
    # Prepare list of group members
    # Get user ids of all users associated with the group
    grp_mem_usrid = getGroupMembersUserIds(group)
    # Get email ids of these users
    usr_list = User.objects.filter(username__in=grp_mem_usrid)
    if request.method == 'POST':
        # Get the sort by value and sort direction
        sortBy = request.POST.__getitem__('sortBy')
	sortDir = request.POST.__getitem__('sortdir')
	if sortBy == 'name':
	    if sortDir == 'asc':
		mem_list = Member.objects.filter(user__in=usr_list).order_by('first_name')
	    else:
		mem_list = Member.objects.filter(user__in=usr_list).order_by('-first_name')
	elif sortBy == 'join':
            if sortDir == 'asc':
		mem_list = Member.objects.filter(user__in=usr_list).order_by('first_name')
	    else:
		mem_list = Member.objects.filter(user__in=usr_list).order_by('-first_name')
    else:
        mem_list = Member.objects.filter(user__in=usr_list)
    
    # Define Paginator
    paginator = Paginator(mem_list, 10)

    
    # Make sure page request is an int. If not, deliver first page.
    try:
        page = int(request.GET.get('page', '1'))
    except ValueError:
        page = 1

    # If page request (9999) is out of range, deliver last page of results.
    try:
        pages = paginator.page(page)
    except (EmptyPage, InvalidPage):
        pages = paginator.page(paginator.num_pages)

    # Get Html List of members
    htmlList = getMembersHtml(pages)
    
    if request.method == 'POST':        
        response = simplejson.dumps({'htmlList': htmlList})
            
    if request.is_ajax():
        return HttpResponse(response,
        content_type="application/javascript")
        
    return render_to_response("groupMembers/member_view.html",
                              {'htmlList': htmlList},
                              context_instance = RequestContext(request))

# Helper function to obtain Group related to a group_web_address
def getGroupInfo(group_web_addr):
    return Group.objects.get(group_web_address= group_web_addr)
    
# Helper function to obtain grou info from group web address
def getGroupFromWebAddr(group_web_addr):
    return Group.objects.get(group_web_address=group_web_addr)
    
# Get All the members associated with the group
def getGroupMembersUserIds(group):
    return Member_Group.objects.filter(group = group).order_by('-join_date').values_list('user_id', flat=True)
    
# Build HTML list of members
# Building the HTMl here will help refreshing the list on server side with paginator
def getMembersHtml(pages):
    dataHtml = []

    # Define Upper Page navigation
    dataHtml.append("<div class='topPagination'>")
    dataHtml.append("<div class='clearbreak noRightBreak'>")
    if pages.has_previous:
        dataHtml.append("<a href='?page=")
        dataHtml.append(str(pages.previous_page_number))
        dataHtml.append("'>previous</a>")
    dataHtml.append("<span>Page ")
    dataHtml.append(str(pages.number))
    dataHtml.append(" of ")
    dataHtml.append(str(pages.paginator.num_pages))
    dataHtml.append("</span>")
    if pages.has_next:
        dataHtml.append("<a href='?page=")
        dataHtml.append(str(pages.next_page_number))
        dataHtml.append("'>next</a>")

    dataHtml.append("</div></div>")

    # Define Member List
    dataHtml.append("<div class='nobreak memberlist'>")
    if pages.object_list:
	for mem in pages.object_list:
	    dataHtml.append("<div class='nobreak singleMember'>")
	    dataHtml.append("<div class='nobreak singleMemberPic'>")
            try:
		dataHtml.append("<img src='http://127.0.0.1:8000/static_media/")
		img_path = mem.photo.url.split('media/')[1]
		# Pull out static media path to image
		dataHtml.append(img_path)
	    except:
		dataHtml.append("<img src='")
	    
            dataHtml.append("' class='singleMemberImg'/>")
            dataHtml.append("</div><div class='nobreak singleMemberInfo'><div>")
            dataHtml.append(mem.first_name)
            dataHtml.append(" ")
            dataHtml.append(mem.last_name)
	    dataHtml.append("</div><div><div>interests: ")
            dataHtml.append(mem.interests)
            dataHtml.append("</div></div></div></div>")
    else:
	dataHtml.append("<div class='nobreak'>No Members Listed</div>")

    # Define Lower Page navigation
    dataHtml.append("</div><div class='nobreak clearbreak'>")
    if pages.has_previous:
        dataHtml.append("<a href='?page=")
        dataHtml.append(str(pages.previous_page_number))
        dataHtml.append("'>previous</a>")	
    dataHtml.append("<span>Page ")
    dataHtml.append(str(pages.number))
    dataHtml.append(" of ")
    dataHtml.append(str(pages.paginator.num_pages))
    dataHtml.append("</span>")	
    if pages.has_next:
        dataHtml.append("<a href='?page=")
        dataHtml.append(str(pages.next_page_number))
        dataHtml.append("'>next</a></div>")

    return mark_safe(u''.join(dataHtml))